#!/usr/bin/env python3
#

import os
import sys
import json
import csv
import base64
from configparser import ConfigParser

TPC_TITLE = 'GCBS-OLTP-C'
TPC_VERSION = '1.3.2'

def _read_log_str(f_path,k):
    with os.popen("cat %s |grep %s|awk -F '=' '{print $2}'" % (f_path,k+'=')) as f:
        return f.read()[:-1]
 
    return ''

def _cwd_dir():
    return os.path.dirname(os.path.abspath(__file__))

def _db_info(db_info_file):
    json_db = dict()

    json_db['type'] = _read_log_str(db_info_file,'db')
    json_db['driver'] = _read_log_str(db_info_file,'driver')
    json_db['conn'] = _read_log_str(db_info_file,'conn')
    json_db['user'] = _read_log_str(db_info_file,'user')
    json_db['version'] = _read_log_str(db_info_file,'version')

    json_db['terminals'] = _read_log_str(db_info_file,'terminals')
    json_db['runMins'] = _read_log_str(db_info_file,'runMins')
    json_db['limitTxnsPerMin'] = _read_log_str(db_info_file,'limitTxnsPerMin')
    json_db['terminals'] = _read_log_str(db_info_file,'terminals')

    json_db['newOrderWeight'] = _read_log_str(db_info_file,'newOrderWeight')
    json_db['paymentWeight'] = _read_log_str(db_info_file,'paymentWeight')
    json_db['orderStatusWeight'] = _read_log_str(db_info_file,'orderStatusWeight')
    json_db['deliveryWeight'] = _read_log_str(db_info_file,'deliveryWeight')
    json_db['stockLevelWeight'] = _read_log_str(db_info_file,'stockLevelWeight')

    # client
    dev_str = _read_log_str(db_info_file,'osCollectorDevices')
    dev_list = dev_str.split(' ')
    ###print(dev_list)
    if len(dev_list) == 2:
        json_db['client_net'] = dev_list[0]
        json_db['client_disk'] = dev_list[1]

    return json_db

# Result Summary.
def _result_summary(res_file):
    
    res = dict()
    res['tpmC'] = 0
    res['tpmTotal'] = 0

    with open(res_file,'r') as f_csv:
        dcts = csv.DictReader(f_csv)
        for dc in dcts:
            if 'tpmC' == dc['tx_name'] or 'tpmTotal' == dc['tx_name']:
                res[dc['tx_name']] = round(float(dc['tx_count']),2)
            else:
                tx_dict = dict()

                tx_dict['tx_count'] = round(float(dc['tx_count']),2)
                tx_dict['tx_percent'] = dc['tx_percent']
                tx_dict['tx_90th'] = dc['tx_90th']
                tx_dict['tx_max'] = dc['tx_max']  
                tx_dict['tx_limit'] = dc['tx_limit'] 
                tx_dict['tx_rbk'] = dc['tx_rbk']
                tx_dict['tx_error'] = dc['tx_error']
                tx_dict['tx_dskipped'] = dc['tx_dskipped']

                res[dc['tx_name']] = tx_dict
                
    return res

def _png_to_base64(png_file):
    with open(png_file, 'rb') as png_file:
        byte_content = png_file.read()
        base64_bytes = base64.b64encode(byte_content)
        return base64_bytes.decode("utf-8")
 
    return ''

def _convert_html_to_pdf(html_path,pdf_path,cwd_dir):
    
    with open(html_path,'r') as f:
        with open(pdf_path,'wb') as pdf:
            print(cwd_dir)
            status = pisa.CreatePDF(src=f,
                                    dest=pdf,
                                    encoding='UTF-8',
                                    default_css=open('{}/h.css'.format(cwd_dir),'r').read(),
                                    images_path=cwd_dir)

            print(status)

## Summary
def _json_report_Summary(report_json,db_info,summary_info):
    summary = [[] for x in range(7)]
    report_json['summary'] = summary

    transaction_list = ['NEW_ORDER','PAYMENT','ORDER_STATUS','STOCK_LEVEL','DELIVERY','DELIVERY_BG']
    
    row = 0

    summary[row] = ['Transaction','Percent','90th','Max','Rollback','Count']
    row = row + 1

    for i in range(len(transaction_list)):
        name = transaction_list[i]
        summary[row].append(name)

        summary[row].append(summary_info[name]['tx_percent'])
        summary[row].append(summary_info[name]['tx_90th'])
        summary[row].append(summary_info[name]['tx_max'])
        summary[row].append(summary_info[name]['tx_rbk'])
        summary[row].append(summary_info[name]['tx_count'])

        row = row + 1

## Details
def _json_report_Details(report_json,db_info,summary_info):
    details = [[] for x in range(9)]
    report_json['details'] = details

    # Title
    details[0] = ['Name','Value']

    details[1] = ['Terminals',db_info['terminals']]
    details[2] = ['Measurement Time','{} mins'.format(db_info['runMins'])]
    details[3] = ['LimitTxnsPerMin',db_info['limitTxnsPerMin']]
    details[4] = ['newOrderWeight',db_info['newOrderWeight']]
    details[5] = ['paymentWeight',db_info['paymentWeight']]
    details[6] = ['orderStatusWeight',db_info['orderStatusWeight']]
    details[7] = ['deliveryWeight',db_info['deliveryWeight']]
    details[8] = ['stockLevelWeight',db_info['stockLevelWeight']]

def _json_report_tier(init_file):
    ini_file = '{}.ini'.format(init_file)
    tier = dict()

    os.system("echo '[Report]' > {}".format(ini_file))
    os.system("cat {} >> {}".format(init_file,ini_file))

    cf = ConfigParser()
    ret_l = cf.read(ini_file, encoding='utf-8')
    if len(ret_l) > 0:
        tier['brandmodel'] = cf.get('Report','brandmodel')
        tier['cpumodel'] = cf.get('Report','cpumodel')
        tier['cpusocks'] = cf.get('Report','cpusocks')
        tier['cpucores'] = cf.get('Report','cpucores')
        tier['cputhrs'] = cf.get('Report','cputhrs')
        tier['memtotal'] = cf.get('Report','memtotal')
        tier['memcount'] = cf.get('Report','memcount')
        tier['memmanu'] = cf.get('Report','memmanu')
        tier['memtype'] = cf.get('Report','memtype')
        tier['memspeed'] = cf.get('Report','memspeed')
        tier['harddisk'] = cf.get('Report','harddisk')
        tier['ethcard'] = cf.get('Report','ethcard')
        tier['osrelease'] = cf.get('Report','osrelease')
        tier['kernelname'] = cf.get('Report','kernelname')

    if os.path.exists(ini_file):
        os.remove(ini_file)
    
    return tier

'''
    ./ReportPy.py my_result_2024-06-07_082806
'''
if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Not foud data_dir')
        exit(1)
    
    report_json = dict()

    log_data_dir = '{}/{}/data'.format(_cwd_dir(),sys.argv[1])

    date_reported = sys.argv[1][10:].replace('-','').replace('_','-')

    db_info = _db_info('{}/{}/run.properties'.format(_cwd_dir(),sys.argv[1]))
    summary_info = _result_summary('{}/tx_summary.csv'.format(log_data_dir))

    ##print(db_info)
    ##print(summary_info)

    # 报告头信息.
    report_json['report_date'] = date_reported
    report_json['report_type'] = TPC_TITLE
    report_json['report_version'] = TPC_VERSION

    report_json['db_name'] = db_info['type']
    report_json['db_version'] = db_info['version']
    report_json['db_logo'] = _png_to_base64("{}/res/3pty.png".format('.'))

    ## 增加主要结果信息.
    report_main_info = [[],[]]
    report_json['main_info'] = report_main_info
 
    report_main_info[0].append('Throughput (tpmC)')
    report_main_info[0].append('Machine(SUT)')
    
    report_main_info[1].append(summary_info['tpmC'])
    ## 之后从tier_a中格式化显示。report_main_info[1].append('')

    report_json['throughput'] = summary_info['tpmC']

    ## 增加主要结果小信息.
    report_main_list = [dict() for x in range(2)]
    report_json['main_list'] = report_main_list

    report_main_list[0]['key'] = 'Terminals'
    report_main_list[0]['value'] = db_info['terminals']

    report_main_list[1]['key'] = 'Measurement Time'
    report_main_list[1]['value'] = '{} mins'.format(db_info['runMins'])

    ## Summary
    _json_report_Summary(report_json,db_info,summary_info)

    ## Details
    _json_report_Details(report_json,db_info,summary_info)

    #Tier A B 信息到json.
    report_json['tier_a'] = _json_report_tier('{}/res/00.mach'.format('.'))
    report_json['tier_b'] = _json_report_tier('{}/res/01.mach'.format('.'))

    report_main_info[1].append('{}\r\n{}'.format(report_json['tier_a']['brandmodel'],report_json['tier_a']['cpumodel']))

    # 事务图.
    report_json['pngs'] = [dict(),dict()]
    report_json['pngs'][0]['png'] = _png_to_base64('{}/{}/tpm_nopm.png'.format(_cwd_dir(),sys.argv[1]))
    report_json['pngs'][1]['png'] = _png_to_base64('{}/{}/latency.png'.format(_cwd_dir(),sys.argv[1]))

    # json报告写入文件.
    report_file_json = '{}/{}/GCBS-OLTP-C-{}-{}.json'.format(_cwd_dir(),sys.argv[1],db_info['type'],date_reported)
    report_file_pdf = '{}/{}/GCBS-OLTP-C-{}-{}.pdf'.format(_cwd_dir(),sys.argv[1],db_info['type'],date_reported)

    with open(report_file_json,'w') as f:
        json.dump(report_json,f)

    # pdf报告写入文件.
    gen_pdf_cmd = '{}/genpdf/oltp_pdf.py {} {}'.format('./',report_file_json,report_file_pdf)
    os.system(gen_pdf_cmd)
